package com.liu.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.liu.mapper.ArticleMapper;
import com.liu.pojo.Article;
import com.liu.pojo.PageBean;
import com.liu.service.ArticleService;
import com.liu.utils.ThreadLocalUtil;
import lombok.experimental.Accessors;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Accessors
    private ArticleMapper articleMapper;

    @Override
    public void add(Article article) {
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId);
        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
//        1、创建PageBean对象
        PageBean<Article> pb = new PageBean<>();
//        2、开启分页查询 PageHelper
        PageHelper.startPage(pageNum, pageSize);//不需要将pageNum和pageSize传到mapper中，将来会自动将pageNum和pageSize传到sql中
//        3、调用mapper查询
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Article> as = articleMapper.list(userId, categoryId, state);
        /*将as强转为Page对象，Page中提供了很多方法，如：getTotal()获取总记录数，getTotalPage()获取总页数，getPageSize()获取每页记录数，
      getRecords()获取当前页的记录集*/
        Page<Article> p = (Page<Article>) as;

//        将查询并且分页完成之后的数据填充到PageBean对象中
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }
}